package com.qing.study.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private RedisTemplate  redisTemplate;

    private static final String TOKEN_PREFIX = "access_token:";
    private static final long TOKEN_EXPIRATION = 2 * 60 * 60 * 1000; // 2 hours

    public String generateAccessToken(String appKey) {
        // 生成一个JWT token或者其他类型的token，这里只是示例
        String accessToken = UUID.randomUUID().toString();

        // 存储到Redis中，并设置过期时间
        redisTemplate.opsForValue().set(TOKEN_PREFIX + accessToken, appKey, TOKEN_EXPIRATION, TimeUnit.MILLISECONDS);

        return accessToken;
    }

    public boolean isValidToken(String accessToken) {
        // 从Redis中获取token对应的appKey
        String appKey = (String) redisTemplate.opsForValue().get(TOKEN_PREFIX + accessToken);

        // 检查appKey是否存在（即token是否有效）
        return appKey != null;
    }
}
